import React, { Component } from 'react'
import { Toast } from 'antd-mobile'
import { List, AutoSizer } from 'react-virtualized'
import './index.sass'
import { getCurrentCity } from '../../utils'
import NavHeader from '../../components/NavHeader'

//数据格式化的方法
const formatCityData = (list) => {
  let cityList = {}
  //遍历list数组
  list.forEach(i => {
    //获取每一个个城市的首字母 
    let first = i.short.substr(0, 1)
    //判断cityList中是否有该分类
    if (cityList[first]) {
      //如果有，直接往该分类中push数据
      cityList[first].push(i)
    } else {
      //如果没有，就先建一个数组，然后把数据添加到数组中
      cityList[first] = [i]
    }
  })
  //获取索引数据
  let cityIndex = Object.keys(cityList).sort()
  return {
    cityList,
    cityIndex
  }
}
const formatCityIndex = (letter) => {
  switch (letter) {
    case '#':
      return '当前定位'
    case 'hot':
      return '热门城市'
    default:
      return letter.toUpperCase()
  }
}
// 有房源的城市
const HOUSE_CITY = ['北京', '上海', '广州', '深圳']
export default class CityList extends Component {
  constructor(props) {
    super(props)
    this.state = {
      cityList: {},
      cityIndex: [],
      // 指定右侧字母索引列表高亮的索引号
      activeIndex: 0
    }
    // 创建ref对象
    this.cityListComponent = React.createRef()
  }
  componentDidMount() {
    this.getCityList()

  }
  async getCityList() {
    let res = await this.$API.get('/area/city?level=1')
    let { cityList, cityIndex } = formatCityData(res)
    let hotCity = await this.$API.get('/area/hot')
    cityList['hot'] = hotCity
    cityIndex.unshift('hot')
    let curCity = await getCurrentCity()
    cityList['#'] = [curCity]
    cityIndex.unshift('#')
    // console.log(cityList, cityIndex, hotCity);
    this.setState({
      cityIndex,
      cityList
    })
    //提前计算list中的每一行高度，实现scrollToRow的精确跳转
    //调用这个方法的时候，需要保证list组件中已经有数据了
    this.cityListComponent.current.measureAllRows()
  }
  onRowsRendered = ({ startIndex }) => {
    if (this.state.activeIndex !== startIndex) {
      this.setState({
        activeIndex: startIndex
      })
    }
  }
  renderCityIndex() {
    const { cityIndex, activeIndex } = this.state
    return cityIndex.map((i, index) =>
      <li className="city_index_item" key={i} onClick={() => this.cityListComponent.current.scrollToRow(index)}>
        <span className={activeIndex === index ? 'index_active' : ''}>
          {i === 'hot' ? '热' : i.toUpperCase()}
        </span>
      </li>
    )
  }

  rowRenderer = ({
    key, // Unique key within array of rows
    index, // 索引号
    isScrolling, // 当前项是否正在滚动中
    isVisible, // 当前项在 List 中是可见的
    style // 注意：重点属性，一定要给每一个行数据添加该样式！作用：指定每一行的位置
  }) => {
    const { cityIndex, cityList } = this.state
    //获取每一行的字母索引
    let letter = cityIndex[index]
    return (
      <div key={key} style={style} className="city">
        <div className="title">{formatCityIndex(letter)}</div>
        {
          cityList[letter].map(i =>
            <div className="name" key={i.value} onClick={() => this.changeCity(i)}>{i.label}</div>
          )
        }
      </div>)
  }
  changeCity({ label, value }) {
    if (HOUSE_CITY.indexOf(label) > -1) {
      //有
      localStorage.setItem('fh_city', JSON.stringify({ label, value }))
      this.props.history.go(-1)
    } else {
      Toast.info('该城市暂无数据', 1, null, false)
    }

  }
  getRowHeight = ({ index }) => {
    //索引标题高度+城市名称高度*城市数量
    const { cityIndex, cityList } = this.state
    let letter = cityIndex[index]
    let length = cityList[letter].length
    return 36 + 50 * length

  }



  render() {
    return (
      <div className="city_list">
        <div style={{marginTop:'-45px'}}>
          <NavHeader>城市选择</NavHeader>
        </div>
        <AutoSizer>
          {
            ({ width, height }) =>
              <List
                ref={this.cityListComponent}
                width={width}
                height={height}
                rowCount={this.state.cityIndex.length}
                rowHeight={this.getRowHeight}
                rowRenderer={this.rowRenderer}
                onRowsRendered={this.onRowsRendered}
                scrollToAlignment="start"
              />
          }
        </AutoSizer>
        <ul className="city_index">
          {
            this.renderCityIndex()
          }
        </ul>
      </div>

    )
  }
}
